package com.example.app2.Template;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

import com.example.app2.R;

public class MyTextView extends View {
    private static final int DEFAULT_LINE_SPACING_EXTRA = 0;
    private static final float DEFAULT_LINE_SPACING_MULTIPLIER = 1.0f;

    private String text;
    private float textSize;
    private int lineSpacingExtra;
    private float lineSpacingMultiplier;

    public MyTextView(Context context) {
        super(context);
        init();
    }

    public MyTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyTextView);
        text = typedArray.getString(R.styleable.MyTextView_text);
        textSize = typedArray.getDimension(R.styleable.MyTextView_textSize, 14);
        lineSpacingExtra = typedArray.getDimensionPixelSize(R.styleable.MyTextView_lineSpacingExtra, DEFAULT_LINE_SPACING_EXTRA);
        lineSpacingMultiplier = typedArray.getFloat(R.styleable.MyTextView_lineSpacingMultiplier, DEFAULT_LINE_SPACING_MULTIPLIER);
        typedArray.recycle();
    }

    private void init() {
        // 初始化行间距属性
        lineSpacingExtra = DEFAULT_LINE_SPACING_EXTRA;
        lineSpacingMultiplier = DEFAULT_LINE_SPACING_MULTIPLIER;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        // 绘制文本
        Paint paint = new Paint();
        paint.setTextSize(textSize);
        paint.setColor(Color.BLACK);

        float lineHeight = paint.getFontMetrics().descent - paint.getFontMetrics().ascent;
        float lineSpacing = lineHeight * lineSpacingMultiplier + lineSpacingExtra;

        String[] lines = text.split("\n");
        float y = 0;
        for (String line : lines) {
            y += lineHeight + lineSpacing;
            canvas.drawText(line, 0, y, paint);
        }
    }

    public void setText(String text) {
        this.text = text;
        invalidate();
    }

    public void setTextSize(float textSize) {
        this.textSize = textSize;
        invalidate();
    }

    public void setLineSpacing(int lineSpacingExtra, float lineSpacingMultiplier) {
        this.lineSpacingExtra = lineSpacingExtra;
        this.lineSpacingMultiplier = lineSpacingMultiplier;
        invalidate();
    }
}
